package com.test.demo.network


import android.text.TextUtils
import com.example.common_library.utils.sp.SpKey

import me.hgj.jetpackmvvm.util.SpUtils
import okhttp3.*
import java.io.IOException


/**
 * 自定义头部参数拦截器，传入heads
 */
class MyHeadInterceptor : Interceptor {

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val builder = request.newBuilder()
        if (!TextUtils.isEmpty(SpUtils.getString(SpKey.DEVICE_NO))) {
            builder.addHeader("DeviceNo", "${SpUtils.getString(SpKey.DEVICE_NO)}")
        }
        if ("GET" == request.method) { // GET方法
            val urlBuilder = request.url.newBuilder()
            // 这里能够添加一些公共get参数
//            urlBuilder.addEncodedQueryParameter("access_token", accessToke02n)
            val httpUrl: HttpUrl = urlBuilder.build()
            // 打印全部get参数
            val paramKeys = httpUrl.queryParameterNames
            for (key in paramKeys) {
                val value = httpUrl.queryParameter(key)
            }
            // 将最终的url填充到request中
            builder.url(httpUrl)
        } else if ("POST" == request.method) {
            val bodyBuilder = FormBody.Builder()
            // 把已有的post参数添加到新的构造器
            if (request.body is FormBody) {
                val formBody = request.body as FormBody?
                for (i in 0 until formBody!!.size) {
                    bodyBuilder.addEncoded(formBody!!.encodedName(i), formBody!!.encodedValue(i))
                }
            }
            // 这里能够添加一些公共post参数
//            bodyBuilder.addEncoded("access_token", accessToken)
            val newBody = bodyBuilder.build()
            builder.post(newBody)
        }
        return chain.proceed(builder.build())
    }

}